package com.neusoft.neps.controller;

import com.neusoft.grid.entity.Mission;
import com.neusoft.neps.entity.user;
import com.neusoft.neps.method.MissionIO;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;


public class SelectGridController {

    @FXML
    private ComboBox<String> provinceComboBox;
    @FXML
    private ComboBox<String> cityComboBox;
    @FXML
    private TextField addressField;
    @FXML
    private Button nextButton;
    @FXML
    private Button backButton;
    @FXML
    private TextField yearField;
    @FXML
    private TextField monthField;
    @FXML
    private TextField dayField;

    private user nowUser;
    private String year;
    private String month;
    private String day;

    @FXML
    private void initialize() {
        // 初始化省份下拉框
        provinceComboBox.getItems().addAll("辽宁省", "吉林省", "河北省", "山东省");

        // 添加省份选择监听器
        provinceComboBox.getSelectionModel().selectedItemProperty().addListener(
                (observable, oldValue, newValue) -> updateCitiesForProvince(newValue));

        // 初始时更新一次城市列表（可选）
        updateCitiesForProvince(provinceComboBox.getValue());
    }

    private void updateCitiesForProvince(String province) {
        cityComboBox.getItems().clear(); // 清空当前城市列表

        if (province == null) {
            return;
        }

        // 根据省份添加对应的城市
        switch (province) {
            case "辽宁省":
                cityComboBox.getItems().addAll("沈阳市", "大连市", "鞍山市");
                break;
            case "吉林省":
                cityComboBox.getItems().addAll("长春市", "吉林市", "四平市");
                break;
            case "河北省":
                cityComboBox.getItems().addAll("石家庄市", "唐山市", "秦皇岛市");
                break;
            case "山东省":
                cityComboBox.getItems().addAll("济南市", "青岛市", "淄博市");
                break;
        }

        cityComboBox.getSelectionModel().selectFirst(); // 可选：自动选择第一个城市
    }

    @FXML
    private void handleNext() throws IOException {
        String province = provinceComboBox.getValue();
        String city = cityComboBox.getValue();
        String address = addressField.getText();

        if (yearField.getText().isEmpty() || monthField.getText().isEmpty() ||
                dayField.getText().isEmpty() || province == null || city == null || address.isEmpty()) {
            showAlert("信息不完整", "请填写所有必填项");
            return;
        }
        try {
            year = yearField.getText();
            month = monthField.getText();
            day = dayField.getText();
        } catch (NumberFormatException e) {
            showAlert("注册失败", "请输入有效的日期");
            return;
        }
        try {
            File file = new File("src/com/neusoft/neps/data/nowUser.txt");
            if (!file.exists() || file.length() == 0) {
                System.out.println("Data file missing or empty");
                file.createNewFile();
            }
            try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
                nowUser = (user) ois.readObject();
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(ex);
            }
        } catch (IOException | RuntimeException e) {
            throw new RuntimeException(e);
        }
        List<Mission> nowMission = new ArrayList<>();
        nowMission.add(new Mission(nowUser.getName(), nowUser.getPhoneNumber(), province + " " + city, address, null,
                null, year, month, day, getMissionId()));
        MissionIO.writeMissions(nowMission, "nowMission.txt");
        try {
            navigateTo("../view/SelectAqiView.fxml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleBack() {
        try {
            navigateTo("../view/LogInView.fxml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getMissionId() {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取年份的后两位（通过格式化）
        String yearLastTwoDigits = currentDate.format(DateTimeFormatter.ofPattern("yy"));
        // 获取月份（1-12）
        int month = currentDate.getMonthValue();
        // 获取日期（1-31）
        int day = currentDate.getDayOfMonth();
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 计算距离当天 0 时的秒数
        long secondsSinceMidnight = now.toLocalTime().toSecondOfDay();
        String Id= yearLastTwoDigits+month+day+secondsSinceMidnight;
        // 组合成 missionId 字符串
        System.out.println("missionId: "+Id);
        return Id;
    }
    // 获取当前日期

    private void navigateTo(String fxmlPath) throws Exception {
        FXMLLoader fxmlLoader = new FXMLLoader();
        Stage stage = (Stage) nextButton.getScene().getWindow();
        URL url = getClass().getResource(fxmlPath);
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = new Scene(root, 600, 400);
        stage.setScene(scene);
        stage.show();
    }

    private void showAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
}